//获取字符串的真实长度（字节长度）
function getTrueLength(str) {

    let len = str.length,
        truelen = 0;

    for (let x = 0; x < len; x++) {
        if (str.charCodeAt(x) > 128) {
            truelen += 2;
        } else {
            truelen += 1;
        }
    }
    return truelen;
}

//按字节长度截取字符串，返回substr截取位置
function cutString(str, leng) {
    let len = str.length,
        tlen = len,
        nlen = 0;

    for (let x = 0; x < len; x++) {
        if (str.charCodeAt(x) > 128) {
            if (nlen + 2 < leng) {
                nlen += 2;
            } else {
                tlen = x;
                break;
            }
        } else {
            if (nlen + 1 < leng) {
                nlen += 1;
            } else {
                tlen = x;
                break;
            }
        }
    }
    return tlen;
}

class CanvasTemplate {
    constructor(id, img, text, width, height) {
        this.canvas = document.getElementById(id);
        this.context = this.canvas.getContext("2d");
        this.text = text;
        this.bgImg = img;
        this.width = width;
        this.height = height;
    }

    canvas = null;
    context = null;
    text = "";
    bgImg = "";
    width = 0;
    height = 0;

    createTemplate(callback) {
        let img = new Image();
        img.onload = () => {

            let canvas = this.canvas;
            let context = this.context;
            let text = this.text;
            let rw = 40;
            let lineheight = 70;
            let font = "400 48px  Helvetica Neue, Helvetica";

            canvas.width = this.width;
            canvas.height = this.height;

            context.drawImage(img, 0, 0, this.width, this.height);

            //画标题
            context.fillStyle = "#000"
            context.font = "600 48px  Helvetica Neue, Helvetica";
            context.textAlign = "center";
            context.fillText("在职证明", 620, 180);

            context.font = font;
            context.textAlign = "left";

            //画内容，类似下面的内容
            //兹证明唐国翔，身份证号码:612422198910190010 
            //自____年__月起在我公司工作至今，现担任本公司
            //糖果箱子的店铺店总经理职位，店铺地址：北京市
            //朝阳区太阳宫南街太阳宫半岛国际公寓12号楼瑞康体检，
            //授权唐国翔在店长直聘招聘，特此证明！
            for (let i = 1; getTrueLength(text) > 0; i++) {
                let tl = cutString(text, rw);
                context.fillText(text.substr(0, tl).replace(/^\s+|\s+$/, ""), 150, i * lineheight + 250);
                text = text.substr(tl);
            }

            //画签名区
            context.fillText("公司盖章：", 600, 1200);
            context.fillText("公司负责人签字：_____", 600, 1300);
            context.fillText("日期：___年 __月__日", 600, 1400);

            let imgSrc = canvas.toDataURL("image/jpeg");

            typeof callback == "function" && callback(imgSrc)
        }
        img.src = this.bgImg;
    }

}

export default CanvasTemplate;